<script setup>
import { ref, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { Edit, Document, Phone, Suitcase, ScaleToOriginal, OfficeBuilding, MoreFilled } from '@element-plus/icons-vue'
import { useUserAuthStore } from '@/stores/userAuth'

const activeMenu = ref('home')
const dialogVisible = ref(false)
const step = ref(0)
const caseType = ref('')
const caseDesc = ref('')
const caseFiles = ref([])
const uploadRef = ref(null)
const fileInputRef = ref(null)
const submitSuccess = ref(false)

// 角色判断
const userAuth = useUserAuthStore()
const userType = computed(() => userAuth.userInfo.user_type || 'user')

// 动态菜单数据
const allMenuItems = [
  { key: 'home', icon: '🏠', label: '首页', path: '/', roles: ['user', 'lawyer'] },
  { key: 'consultation', icon: '💬', label: '法律咨询', path: '/messages', roles: ['user'] },
  {
    key: 'cases',
    icon: '💼',
    label: '案件管理',
    path: '/case',
    roles: ['user', 'lawyer'],
    children: [
      { key: 'case-list', label: '案件列表', path: '/case' },
      { key: 'case-apply', label: '申请案件', path: '/case-apply' }
    ]
  },
  { key: 'ai-assistant', icon: '🤖', label: 'AI助手', path: '/ai-qa', roles: ['user', 'lawyer'] },
  { key: 'user-manage', icon: '👤', label: '用户管理', path: '/user', roles: ['user', 'lawyer'],
    children: [
      { key: 'user-list', label: '用户列表', path: '/user-list' }
    ]
  },
  { key: 'lawyers', icon: '👨‍💼', label: '律师团队', path: '/lawyer-team', roles: ['user'] },
  { key: 'resources', icon: '📚', label: '法律资源', path: '/legal-resource', roles: ['user'] },
  { key: 'news', icon: '📰', label: '法律资讯', path: '/legal-news', roles: ['user'] },
  { key: 'contact', icon: '📞', label: '联系我们', path: '/contact-us', roles: ['user'] }
]

// 计算当前角色可见菜单
const menuItems = computed(() => allMenuItems.filter(item => item.roles.includes(userType.value)))

const router = useRouter()

function handleMenuClick(item) {
  activeMenu.value = item.key
  if (item.path) {
    router.push(item.path)
    console.log('点击菜单', item.path)
  }
}

function handleSubMenuClick(command) {
  activeMenu.value = command.key
  if (command.path) {
    router.push(command.path)
    console.log('点击子菜单', command.path)
  }
}

function setActiveMenu(key) {
  activeMenu.value = key
}

function nextStep() {
  if (step.value < 2) step.value++
}
function prevStep() {
  if (step.value > 0) step.value--
}

function triggerFileInput() {
  fileInputRef.value && fileInputRef.value.click()
}

function handleCaseFilesChange(file, fileList) {
  // 只处理新增的文件
  if (fileList) {
    caseFiles.value = fileList.map(f => processFile(f))
  } else if (file) {
    caseFiles.value.push(processFile(file))
  }
}
function handleCaseFilesChangeByInput(e) {
  const files = Array.from(e.target.files)
  caseFiles.value = files.map(f => processFile({ raw: f, name: f.name, uid: f.name + Date.now() }))
  // 关键：重置 input 的 value，防止下次无法触发或多次弹窗
  e.target.value = ''
}
function beforeCaseFileUpload(file) {
  // 可加类型/大小校验
  return true
}
function processFile(file) {
  const isImage = file.raw ? file.raw.type.startsWith('image/') : file.type && file.type.startsWith('image/')
  let url = ''
  if (isImage) {
    const raw = file.raw || file
    url = URL.createObjectURL(raw)
  }
  return {
    name: file.name,
    uid: file.uid || file.name + Date.now(),
    isImage,
    url,
    raw: file.raw || file
  }
}
function removeCaseFile(idx) {
  caseFiles.value.splice(idx, 1)
}
function submitCase() {
  // 提交案件逻辑
  // dialogVisible.value = false
  step.value = 0
  caseType.value = ''
  caseDesc.value = ''
  caseFiles.value = []
  submitSuccess.value = true
}
function closeDialog() {
  dialogVisible.value = false
  submitSuccess.value = false
}
</script>

<template>
  <aside class="sidebar-left">
    <nav class="sidebar-nav">
      <div class="nav-section">
        <h3 class="nav-title">导航菜单</h3>
        <el-menu
          :router="true"
          :default-active="$route.path"
          class="nav-menu"
          background-color="transparent"
          text-color="#333"
          active-text-color="#495060"
        >
          <template v-for="item in menuItems" :key="item.key">
            <!-- 有子菜单的项目 -->
            <el-sub-menu v-if="item.children" :index="item.key">
              <template #title>
                <span class="nav-icon">{{ item.icon }}</span>
                <span class="nav-label">{{ item.label }}</span>
              </template>
              <el-menu-item
                v-for="child in item.children"
                :key="child.key"
                :index="child.path"
              >
                {{ child.label }}
              </el-menu-item>
            </el-sub-menu>
            <!-- 没有子菜单的项目 -->
            <el-menu-item
              v-else
              :index="item.path"
            >
              <span class="nav-icon">{{ item.icon }}</span>
              <span class="nav-label">{{ item.label }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </div>
      
      <div class="nav-section">
        <h3 class="nav-title">快速入口</h3>
        <div class="quick-actions">
          <el-button class="quick-btn quick-btn-primary" size="small">
            <span class="quick-btn-content">
              <el-icon class="btn-icon"><Edit /></el-icon>
              <span class="btn-text">在线咨询</span>
            </span>
          </el-button>
          <el-button class="quick-btn quick-btn-success quick-btn-case" size="small" @click="dialogVisible = true">
            <span class="quick-btn-content">
              <el-icon class="btn-icon"><Document /></el-icon>
              <span class="btn-text">案件提交</span>
            </span>
          </el-button>
          <el-button class="quick-btn quick-btn-warning quick-btn-emergency" size="small">
            <span class="quick-btn-content">
              <el-icon class="btn-icon"><Phone /></el-icon>
              <span class="btn-text">紧急联系</span>
            </span>
          </el-button>
        </div>
        <!-- 案件提交三步弹窗 -->
        <el-dialog v-model="dialogVisible" title="案件提交" width="600px" @close="closeDialog">
          <template v-if="!submitSuccess">
            <el-steps :active="step" finish-status="success" align-center style="margin-bottom: 24px;">
              <el-step title="案件类型" />
              <el-step title="案情描述" />
              <el-step title="提交材料" />
            </el-steps>
            <!-- 步骤一：案件类型 -->
            <div v-if="step === 0">
              <div style="font-weight: bold; font-size: 22px; margin-bottom: 16px;">案件类型</div>
              <el-radio-group v-model="caseType" style="width: 100%;">
                <el-radio-button value="民事案件">
                  <el-icon style="margin-right: 8px;"><Suitcase /></el-icon>
                  民事案件
                </el-radio-button>
                <el-radio-button value="刑事案件">
                  <el-icon style="margin-right: 8px;"><ScaleToOriginal /></el-icon>
                  刑事案件
                </el-radio-button>
                <el-radio-button value="行政案件">
                  <el-icon style="margin-right: 8px;"><OfficeBuilding /></el-icon>
                  行政案件
                </el-radio-button>
                <el-radio-button value="其他">
                  <el-icon style="margin-right: 8px;"><MoreFilled /></el-icon>
                  其他
                </el-radio-button>
              </el-radio-group>
              <div style="margin-top: 24px;">
                <el-button type="primary" @click="nextStep" :disabled="!caseType">下一步</el-button>
              </div>
            </div>
            <!-- 步骤二：案情描述 -->
            <div v-else-if="step === 1">
              <div style="font-weight: bold; font-size: 22px; margin-bottom: 16px;">案情描述</div>
              <el-input
                type="textarea"
                v-model="caseDesc"
                :rows="6"
                placeholder="请详细描述案情..."
                style="width: 100%; margin-bottom: 24px;"
              />
              <el-button @click="prevStep">上一步</el-button>
              <el-button type="primary" @click="nextStep" :disabled="!caseDesc">下一步</el-button>
            </div>
            <!-- 步骤三：上传材料 -->
            <div v-else-if="step === 2">
              <div style="font-weight: bold; font-size: 22px; margin-bottom: 16px;">上传证据材料</div>
              <el-upload
                class="upload-demo"
                action=""
                :show-file-list="false"
                :on-change="handleCaseFilesChange"
                :before-upload="beforeCaseFileUpload"
                multiple
                :auto-upload="false"
                ref="uploadRef"
              >
                <el-button size="small" type="primary" @click="triggerFileInput">选择文件/文件夹</el-button>
              </el-upload>
              <input
                ref="fileInputRef"
                type="file"
                multiple
                webkitdirectory
                style="display: none;"
                @change="handleCaseFilesChangeByInput"
              />
              <div style="margin-top: 10px;">
                <template v-if="caseFiles.length">
                  <div v-for="(file, idx) in caseFiles" :key="file.uid || file.name" style="display: flex; align-items: center; margin-bottom: 8px;">
                    <el-image
                      v-if="file.isImage"
                      :src="file.url"
                      style="width: 60px; height: 60px; margin-right: 10px;"
                      fit="cover"
                    />
                    <span v-else style="width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; background: #f5f5f5; margin-right: 10px;">{{ file.name }}</span>
                    <el-button size="mini" type="danger" @click="removeCaseFile(idx)">移除</el-button>
                  </div>
                </template>
                <span v-else>无文件</span>
              </div>
              <div style="margin-top: 24px;">
                <el-button @click="prevStep">上一步</el-button>
                <el-button type="primary" @click="submitCase">提交申请</el-button>
              </div>
            </div>
          </template>
          <template v-else>
            <div class="submit-success-panel">
              <div class="success-icon">
                <svg viewBox="0 0 64 64" width="64" height="64"><circle cx="32" cy="32" r="32" fill="#67C23A"/><polyline points="18,34 28,44 46,22" fill="none" stroke="#fff" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/></svg>
              </div>
              <div class="success-title">提交成功</div>
              <div class="success-desc">感谢您的案件提交，我们会尽快安排专业律师与您联系！</div>
              <el-button type="primary" @click="closeDialog" style="margin-top: 24px;">返回</el-button>
            </div>
          </template>
        </el-dialog>
      </div>

      <div class="nav-section">
        <h3 class="nav-title">服务统计</h3>
        <div class="stats">
          <div class="stat-item">
            <div class="stat-number">1,234</div>
            <div class="stat-label">已处理案件</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">56</div>
            <div class="stat-label">专业律师</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">98%</div>
            <div class="stat-label">满意度</div>
          </div>
        </div>
      </div>
    </nav>
  </aside>
</template>

<style scoped>
.sidebar-left {
  padding-top: 56px;
  width: 280px;
  background: #fff;
  border-right: 1px solid #e8eaec;
  overflow-y: auto;
  flex-shrink: 0;
  height: 100%;
  min-height: 100%;
}

.sidebar-nav {
  padding: 20px 0;
  height: 100%;
  overflow-y: auto;
}

.nav-section {
  margin-bottom: 32px;
  padding: 0 20px;
}

.nav-title {
  font-size: 14px;
  color: #999;
  margin-bottom: 16px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.nav-menu {
  list-style: none;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 4px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}
.el-dropdown-link {
  cursor: pointer;
  margin-left: auto;
  color: inherit;
}
.el-dropdown-link:hover {
  color: #409eff;
}

.nav-item:hover {
  background: #f0f9ff;
  color: #2d8cf0;
}

.nav-item.active {
  background: #2d8cf0;
  color: #fff;
}

.nav-icon {
  font-size: 18px;
  margin-right: 12px;
  width: 20px;
  text-align: center;
}

.nav-label {
  font-size: 14px;
  font-weight: 500;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 0;
}

.quick-btn {
  display: flex !important;
  align-items: center !important;
  justify-content: flex-start !important;
  width: 100% !important;
  text-align: left !important;
  height: 48px !important;
  font-size: 18px !important;
  font-weight: 500 !important;
  border-radius: 8px !important;
  margin-bottom: 14px !important;
  padding: 0 0px !important;
  box-sizing: border-box !important;
  border: none !important;
  box-shadow: none !important;
  background: #4ea1ff !important; /* 默认蓝色，可用不同class覆盖 */
  color: #fff !important;
}

.quick-btn-success {
  background: #5ac44e !important;
}
.quick-btn-warning {
  background: #e6a23c !important;
}
.quick-btn-primary {
  background: #409eff !important;
}

.quick-btn-case,
.quick-btn-emergency {
  margin-left: 0 !important;
}

.quick-actions .quick-btn:last-child {
  margin-bottom: 0 !important;
}

.quick-btn-content {
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
}

.btn-icon {
  width: 32px;
  min-width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 14px;
  font-size: 22px;
  flex-shrink: 0;
}

.btn-text {
  flex: 1;
  display: flex;
  align-items: center;
  height: 100%;
  font-size: 18px;
  font-weight: 500;
  line-height: 1;
}

.stats {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #2d8cf0;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.submit-success-panel {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0 32px 0;
}
.success-icon {
  margin-bottom: 18px;
}
.success-title {
  font-size: 2rem;
  font-weight: bold;
  color: #67C23A;
  margin-bottom: 12px;
}
.success-desc {
  font-size: 1.1rem;
  color: #666;
  margin-bottom: 8px;
  text-align: center;
  max-width: 320px;
}

/* 撤销美化步骤相关样式 */
.case-steps {}
.case-step-panel {}
.case-step-title {}
.case-step-desc {}
.case-radio-btn {}
.case-btns {}
.case-file-item {}
.case-file-name {}
.case-file-empty {}

@media (max-width: 992px) {
  .sidebar-left {
    width: 100%;
    height: auto;
    max-height: 300px;
    border-right: none;
    border-bottom: 1px solid #e8eaec;
  }
}
</style> 